package com.ziytek.web.citizen.listener;

import com.google.gson.Gson;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.event.VersionEvent;
import com.ziytek.web.citizen.mapper.VersionInfoMapper;
import com.ziytek.web.citizen.pojo.ProgramVersionInfo;
import com.ziytek.web.citizen.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @author fenghx
 * @version v1.0
 * @className MessageListener
 * @descripton 功能描述
 * @date 2023/4/11 14:58
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VersionListener {

    private final Gson gson;
    private final VersionInfoMapper versionInfoMapper;

    @Async("myAsyncExecutor")
    @EventListener
    @Order(ServerConstant.DATA_TYPE_LEN_1)
    public void versionListener(VersionEvent event) {
        if (event == null || StringUtil.isEmpty(event.getCabinetNo()) || CollectionUtils.isEmpty(event.getVersionMap())) {
            var cabinetNo = event != null && StringUtil.isNotEmpty(event.getCabinetNo()) ? event.getCabinetNo() : "未知设备";
            log.info("设备[{}]上送分控程序版本数据为空!", cabinetNo);
            return;
        }

        var cabinetNo = event.getCabinetNo();
        var versionMap = event.getVersionMap();

        var info = versionInfoMapper.findFirstByCabinetNoOrderByCreateTimeDesc(cabinetNo);
        if (info == null) {
            info = new ProgramVersionInfo();
            info.setCabinetNo(cabinetNo);
            info.setCreateTime(System.currentTimeMillis());
            info.setUpdateTime(System.currentTimeMillis());
            info.setControlVersionMapJson(gson.toJson(versionMap));
            versionInfoMapper.versionInfoSave(info);
            return;
        }

        var oldVersionMapJson = info.getControlVersionMapJson();
        var newVersionMapJson = gson.toJson(versionMap);
        if (StringUtil.isNotEmpty(oldVersionMapJson) && oldVersionMapJson.equals(newVersionMapJson)) {
            return;
        }

        info.setControlVersionMapJson(newVersionMapJson);
        info.setUpdateTime(System.currentTimeMillis());

        versionInfoMapper.versionInfoUpdate(info);
    }
}
